//
//  SXOAuthController.m
//  Weibo1
//
//  Created by dfpo on 15/3/16.
//  Copyright (c) 2015年 dfpo. All rights reserved.
//

#import "SXOAuthController.h"
#import "MBProgressHUD+MJ.h"
#import "SXAccountTool.h"
#import "AFNetWorking.h"
@interface SXOAuthController ()<UIWebViewDelegate>

@end

@implementation SXOAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    // establish a UIWebView
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    webView.delegate = self;
    [self.view addSubview:webView];
    
    // use this webView load web
    // 请求地址：https://api.weibo.com/oauth2/authorize
    /* 请求参数：
     client_id	true	string	申请应用时分配的AppKey。3249004814
     redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。http://songxing10000.blog.163.com */
     
//    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=3249004814&redirect_uri=http://songxing10000.blog.163.com"];
    
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=2507721026&redirect_uri=http://my.oschina.net/u/2333251"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}
#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [MBProgressHUD hideHUD];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [MBProgressHUD showMessage:@"正在加载..."];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [MBProgressHUD hideHUD];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *urlString = request.URL.absoluteString;
    // judge is the invoke address
    NSRange range = [urlString rangeOfString:@"code="];
    if (range.length != 0) {
        int fromIndex = (int)range.location + (int)range.length;
        NSString *code = [urlString substringFromIndex:fromIndex];
        // use the code to get a accessToken
        [self accessTokenWithCode: code];
        return NO;
    }
    
    return YES;
}
#pragma mark - token
- (void)accessTokenWithCode:(NSString *)code {
    /*
     URL：https://api.weibo.com/oauth2/access_token
     
     请求参数：
     client_id：申请应用时分配的AppKey 3249004814
     client_secret：申请应用时分配的AppSecret  16227ec126df1521f469c7c5af545d60
     grant_type：使用authorization_code
     redirect_uri：授权成功后的回调地址 http://songxing10000.blog.163.com
     code：授权成功后返回的code code
     */
    
    // use afn manager
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    // params
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
//    params[@"client_id"] = @"3249004814";
//    params[@"client_secret"] = @"16227ec126df1521f469c7c5af545d60";
//    params[@"grant_type"] = @"authorization_code";
//    params[@"redirect_uri"] = @"http://songxing10000.blog.163.com";
//    params[@"code"] = code;

    
    
    
    
//    App Key：2507721026
//    App Secret：dd92b400310fa5eb9e2fe5bc9c1caa6c
//    创建时间：2015-04-05
//    应用地址：http://my.oschina.net/u/2333251
    
    
    params[@"client_id"] = @"2507721026";
    params[@"client_secret"] = @"dd92b400310fa5eb9e2fe5bc9c1caa6c";
    params[@"grant_type"] = @"authorization_code";
    params[@"redirect_uri"] = @"http://my.oschina.net/u/2333251";
    params[@"code"] = code;
    
    
    // request
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params
        success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
            SXLog(@"请求成功-%@", responseObject);
            [MBProgressHUD hideHUD];
        
            SXAccount *account = [SXAccount accountWithDict:responseObject];
            [SXAccountTool saveAccount:account];
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [window switchRootViewController];
            
        }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD hideHUD];
            SXLog(@"请求失败-%@", error);
    }];
}
@end
